<template>
	<xn-form-container
		title="新增短信模版"
		:width="550"
		:visible="visible"
		:destroy-on-close="true"
		@close="onClose"
	>
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
			<a-form-item label="模版名称" name="templateName">
				<a-input v-model:value="formData.templateName" placeholder="请输入模版名称" allow-clear/>
			</a-form-item>
			<a-form-item label="模版编码" name="templateCode">
				<a-input v-model:value="formData.templateCode" placeholder="请输入模版编码" allow-clear/>
			</a-form-item>
			<a-form-item label="模版内容" name="templateContent">
				<a-textarea v-model:value="formData.templateContent" placeholder="请输入模版内容"
							:auto-size="{ minRows: 10, maxRows:15 }"/>
			</a-form-item>
			<a-form-item label="供应商优先级" name="supplierOrder">
				<VueDraggable v-model="supplierList" @end="onEnd">
					<a-button v-for="item in supplierList" :key="item.id">{{ item.supplierName }}</a-button>
				</VueDraggable>
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button class="xn-mr8" @click="onClose">关闭</a-button>
			<a-button type="primary" @click="onSubmit" :loading="submitLoading">保存</a-button>
		</template>
	</xn-form-container>
</template>

<script setup>
import {required} from '@/utils/formRules'
import smsTemplateApi from "@/api/tjzy/sms/smsTemplateApi";
import {VueDraggable} from 'vue-draggable-plus';
import supplierApi from "@/api/tjzy/supplier/supplierApi";
// 默认是关闭状态
const visible = ref(false)
const emit = defineEmits({successful: null})
const formRef = ref()
const supplierList = ref([])
// 表单数据
const submitLoading = ref(false)
const formData = ref({
	supplierOrder: undefined
})

// 打开抽屉
const onOpen = (record) => {
	visible.value = true
	formData.value = Object.assign(formData.value, record)
	supplierApi.list().then((res) => {
		supplierList.value = res
		if (record) {
			const orderMap = new Map(record.supplierOrder.split(',').map((code, index) => [code, index]));
			supplierList.value.sort((a, b) => {
				return (orderMap.get(a.supplierCode) || 0) - (orderMap.get(b.supplierCode) || 0);
			});
		}
		formData.value.supplierOrder = supplierList.value.map(item => item.supplierCode).join(',');
	})
}
// 关闭抽屉
const onClose = () => {
	formData.value = {}
	visible.value = false
}

const onEnd = () => {
	formData.value.supplierOrder = supplierList.value.map(item => item.supplierCode).join(',');
}

// 默认要校验的
const formRules = {
	templateName: [required('请选择项目')],
	templateCode: [required('请选择项目')],
	templateContent: [required('请选择项目')],
	supplierOrder: [required('请输入手机号')]
}

// 验证并提交数据
const onSubmit = () => {
	formRef.value
		.validate()
		.then(() => {
			submitLoading.value = true
			smsTemplateApi.addOrEdit(formData.value).finally(() => {
				onClose()
				emit('successful')
				submitLoading.value = false
			})
		})
}

// 调用这个函数将子组件的一些数据和方法暴露出去
defineExpose({
	onOpen
})
</script>
